package cn.study.luckyinfrastructure.gateway.iml;

import cm.study.config.enums.LdExeceptionEnum;
import cm.study.config.util.AssertUtil;
import cn.study.luckyclient.dto.query.PrizeListByParamQuery;
import cn.study.luckydomain.gateway.PrizeGateway;
import cn.study.luckydomain.prize.PrizeEntity;
import cn.study.luckyinfrastructure.convertor.PrizeConvertor;
import cn.study.luckyinfrastructure.gateway.iml.dataObject.PrizeDB;
import cn.study.luckyinfrastructure.gateway.iml.mapper.PrizeMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@AllArgsConstructor
public class PrizeGatewayImpl implements PrizeGateway {
    private final PrizeMapper prizeMapper;
    @Override
    public PrizeEntity add(PrizeEntity prizeEntity) {
        PrizeDB prizeDB = PrizeConvertor.toPrizeDB(prizeEntity);
        int insert = prizeMapper.insert(prizeDB);
        AssertUtil.isTrue(insert<1, LdExeceptionEnum.ADD_ERROR.getDescription());
        return PrizeConvertor.toEntity(prizeDB);
    }

    @Override
    public PrizeEntity update(PrizeEntity prizeEntity) {
        PrizeDB prizeDB = PrizeConvertor.toPrizeDB(prizeEntity);
        QueryWrapper<PrizeDB> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",prizeDB.getId());
        int update = prizeMapper.update(prizeDB, queryWrapper);
        AssertUtil.isTrue(update<1, LdExeceptionEnum.UPDATE_ERROR.getDescription());
        return PrizeConvertor.toEntity(prizeDB);
    }

    @Override
    public IPage<PrizeEntity> query(PrizeListByParamQuery prizeListByParamQuery) {
        IPage<PrizeDB> page=new Page<>();
        LambdaQueryWrapper<PrizeDB> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(prizeListByParamQuery.getId()!=null,PrizeDB::getId,prizeListByParamQuery.getId());
        lambdaQueryWrapper.eq(prizeListByParamQuery.getType()!=null,PrizeDB::getType,prizeListByParamQuery.getType());
        lambdaQueryWrapper.like(prizeListByParamQuery.getPrizeName()!=null,PrizeDB::getPrizeName,prizeListByParamQuery.getPrizeName());
        prizeMapper.selectPage(page, lambdaQueryWrapper);
        return page.convert(PrizeConvertor::toEntity);

    }

    @Override
    public int deductionInventory(Long prizeId, Integer number) {
       return prizeMapper.dedutionInventory(prizeId,number);
    }
}
